package com.example.finance_manager.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.finance_manager.db.SQLiteHelper;
import com.example.finance_manager.models.Room;

import java.util.ArrayList;
import java.util.List;

public class RoomDao {
    private final SQLiteHelper sqLiteHelper;
    private SQLiteDatabase db;

    public RoomDao(Context context) {
        sqLiteHelper = new SQLiteHelper(context);
    }

    public long add(Room room) {
        db = sqLiteHelper.getWritableDatabase();
        ContentValues cv = getContentValues(room);
        return db.insert("room", null, cv);
    }

    public List<Room> findAll() {
        List<Room> list = new ArrayList<Room>();
        db = sqLiteHelper.getReadableDatabase();
        Cursor cursor = db.query("room", new String[]{
                "id", "type", "size", "window", "bed", "capacity", "used"
        }, null, null, null, null, null);
        while (cursor.moveToNext()) {
            Room room = new Room();
            room.setId(cursor.getInt(0));
            room.setType(cursor.getString(1));
            room.setSize(cursor.getString(2));
            room.setWindow(cursor.getInt(3));
            room.setBed(cursor.getString(4));
            room.setCapacity(cursor.getInt(5));
            room.setUsed(cursor.getInt(6));
            list.add(room);
        }
        return list;
    }

    private void update(Room room) {
        Integer id = (Integer) room.getId();
        db = sqLiteHelper.getWritableDatabase();
        ContentValues cv = getContentValues(room);
        db.update("room", cv, "id = ?", new String[]{id.toString()});
    }

    private ContentValues getContentValues(Room room) {
        ContentValues cv = new ContentValues();
        cv.put("type", room.getType());
        cv.put("size", room.getSize());
        cv.put("window", room.getWindow());
        cv.put("bed", room.getBed());
        cv.put("capacity", room.getCapacity());
        cv.put("used", room.getUsed());
        return cv;
    }
}
